package com.kanshu.ksgb.fastread.doudou.module.message.manager;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.NonNull;

import com.kanshu.ksgb.fastread.doudou.app.Xutils;
import com.kanshu.ksgb.fastread.doudou.app.db.KanShuDbHelper;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.MessageBean;
import com.kanshu.ksgb.fastread.doudou.common.util.JsonUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wcy on 2017\6\26 0026.
 */

public class MessageDao {
    public static final String MESSAGE_ID = "message_id";
    public static final String TIME = "createtime";
    public static final String EXTRAS = "extras";
    public static final String MESSAGE_ENTITY = "message_entity";
    public static final String IS_READ = "is_read";
    private String mTableName;
    public MessageDao(String userId) {
        mTableName = "message_" + userId;
        createTable();
        updateTable();
    }

    public static Uri getContentUri(String userId) {
        return Uri.parse("content://" + Xutils.getContext().getPackageName() + "/message/" + userId);
    }

    /**
     * 动态创建表
     */
    private void createTable() {
        SQLiteDatabase db = new KanShuDbHelper(Xutils.getContext()).getWritableDatabase();
        String s = createTableSQL();
        db.execSQL(s);
        db.close();
    }

    /**
     * 升级表结构 ，这个方法主要用于在表结构变化的时候调用，由于是动态生成的表，所以只有采用这样的方式去升级表结构
     */
    private void updateTable() {
        // TODO: 使用时先检查是否存储该column，然后进行增删改查，调用StorageUtils.checkColumnExists

    }

    @NonNull
    public String createTableSQL() {
        StringBuilder sql = new StringBuilder();
        sql.append("CREATE TABLE IF NOT EXISTS ").append(mTableName)
                .append("(_id INTEGER PRIMARY KEY,")
                .append(MESSAGE_ID).append(" TEXT,")
                .append(TIME).append(" TEXT,")
                .append(EXTRAS).append(" TEXT,")
                .append(IS_READ).append(" INTEGER,")
                .append(MESSAGE_ENTITY).append(" TEXT)");
        return sql.toString();
    }

    public void insertOrUpdate(MessageBean bean) {
        SQLiteDatabase db = new KanShuDbHelper(Xutils.getContext()).getWritableDatabase();
        db.replace(mTableName, null, toValues(bean));
        notifyChange();
        db.close();
    }

    private ContentValues toValues(MessageBean bean) {
        ContentValues values = new ContentValues();
        values.put(MESSAGE_ID, bean.message_id);
        values.put(MESSAGE_ENTITY, JsonUtils.bean2Json(bean));
        values.put(TIME, bean.createtime + "");
        values.put(IS_READ, bean.is_read);
        return values;
    }

    private void notifyChange() {
//        Xutils.getContext().getContentResolver().notifyChange(getContentUri(UserUtils.getUserId()), null);
    }

    /**
     * @param limit
     * @param offset
     * @return
     */
    public List<MessageBean> queryByLimitOffset(int limit, int offset) {
        List<MessageBean> list ;
        SQLiteDatabase db = new KanShuDbHelper(Xutils.getContext()).getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from " + mTableName + " order by _id limit " + limit + " offset " + offset, null);
        list = toBeans(cursor);
        if (cursor != null) {
            cursor.close();
        }
        db.close();
        return list;
    }

    public int getMessageCount() {
        SQLiteDatabase db = new KanShuDbHelper(Xutils.getContext()).getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from " + mTableName, null);
        int count = 0;
        while (cursor != null && cursor.moveToNext()) {
           count++;
        }
        db.close();
        return count;
    }

    public List<MessageBean> queryAll() {
        List<MessageBean> list = new ArrayList<>();
        SQLiteDatabase db = new KanShuDbHelper(Xutils.getContext()).getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from " + mTableName, null);
        list = toBeans(cursor);
        if (cursor != null) {
            cursor.close();
        }
        db.close();
        return list;
    }

    private List<MessageBean> toBeans(Cursor cursor) {
        List<MessageBean> list = new ArrayList<>();
        while (cursor != null && cursor.moveToNext()) {
            String s = cursor.getString(cursor.getColumnIndex(MESSAGE_ENTITY));
            int is_read = cursor.getInt(cursor.getColumnIndex(IS_READ));
            MessageBean messageBean = JsonUtils.json2Bean(s, MessageBean.class);
            messageBean.is_read = is_read;
            list.add(messageBean);
        }
        return list;
    }

    public void deleteByMsgId(String msgId) {
        SQLiteDatabase db = new KanShuDbHelper(Xutils.getContext()).getWritableDatabase();
        db.delete(mTableName, MESSAGE_ID + "=?", new String[]{msgId});
        db.close();
    }
}
